package com.jack.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jack.mapper.ClazzMapper;
import com.jack.mapper.StudentMapper;
import com.jack.pojo.Clazz;
import com.jack.queryParam.ClazzQueryParam;
import com.jack.result.PageResult;
import com.jack.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 班级服务接口实现类
 */
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;
    /**
     * 新增班级
     *
     * @param clazz
     */
    public void addClazz(Clazz clazz) {
        // 补全参数
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazz(clazz);
    }

    /**
     * 删除班级
     *
     * @param id
     */
    public void deleteClazz(Integer id) {
        // 判断班级中是否还有学生，如果有学生，则不能删除
        if (studentMapper.countStuOfClazz(id)>0) {
            throw new RuntimeException("该班级中还有学生，不能删除");
        }
        clazzMapper.deleteClazz(id);
    }


    /**
     * 修改班级
     *
     * @param clazz
     */
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazz(clazz);
    }

    /**
     * 分页查询班级
     * @param clazzQueryParam
     * @return
     */
    public PageResult<Clazz> pageClazzs(ClazzQueryParam clazzQueryParam) {
        // 设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());

        // 查询
        List<Clazz> clazzList = clazzMapper.pageClazzs(clazzQueryParam);

        // 封装分页结果
        Page<Clazz> p = (Page<Clazz>) clazzList;

        return new PageResult<>(p.getTotal(),p.getResult());
    }

    /**
     * 根据id查询班级
     * @param id
     * @return
     */
    public Clazz getClazzById(Integer id) {
        return clazzMapper.getClazzById(id);
    }

    /**
     * 获取班级列表
     * @return
     */
    public List<Clazz> getClazzsList() {
        return clazzMapper.getClazzsList();
    }
}
